import $store from '@/sheep/store';
import $helper from '@/sheep/helper';
import dayjs from 'dayjs';
import {
	ref
} from 'vue';
import test from '@/sheep/helper/test.js';
import $api from '@/sheep/api';

// 打开授权弹框
export function showAuthModal(type = 'accountLogin') {
	const modal = $store('modal');
	setTimeout(() => {
		modal.$patch((state) => {
			state.auth = type;
		});
	}, 500);
}

// 关闭授权弹框
export function closeAuthModal() {
	$store('modal').$patch((state) => {
		state.auth = '';
	});
}

/**
 * @description 打开分享弹框
 * @param {Object} type 弹窗类型
 */
export function showShareModal(type) {
	$store('modal').$patch((state) => {
		switch (type) {
			case 'linkShare':
				state.linkShare = true;
				break;
			case 'posterShare':
				state.posterShare = true;
				break;
		}
	});
}

// 关闭分享弹框
export function closeShareModal(type) {
	$store('modal').$patch((state) => {
		switch (type) {
			case 'linkShare':
				state.linkShare = false;
				break;
			case 'posterShare':
				state.posterShare = false;
				break;
		}
	});
}

// 发送短信验证码  60秒
export function getSmsCode(event, mobile = '') {
	const modalStore = $store('modal');
	const lastSendTimer = modalStore.lastTimer[event];

	if (typeof lastSendTimer === 'undefined') {
		$helper.toast('短信发送事件错误');
		return;
	}

	const duration = dayjs().unix() - lastSendTimer;
	const canSend = duration >= 60;

	if (!canSend) {
		$helper.toast('请稍后再试');
		return;
	}

	if (!test.mobile(mobile)) {
		$helper.toast('手机号码格式不正确');
		return;
	}

	// 发送验证码 + 更新上次发送验证码时间
	$api.app
		.sendSms({
			mobile,
			event,
		})
		.then((res) => {
			if (res.error === 0) {
				modalStore.$patch((state) => {
					state.lastTimer[event] = dayjs().unix();
				});
			}
		});
}

// 获取短信验证码倒计时 -- 60秒
export function getSmsTimer(event, mobile = '') {
	const modalStore = $store('modal');
	const lastSendTimer = modalStore.lastTimer[event];

	if (typeof lastSendTimer === 'undefined') {
		$helper.toast('短信发送事件错误');
		return;
	}

	const duration = ref(dayjs().unix() - lastSendTimer - 60);
	const canSend = duration.value >= 0;

	if (canSend) {
		return '获取验证码';
	}

	if (!canSend) {
		setTimeout(() => {
			duration.value++;
		}, 1000);
		return -duration.value.toString() + ' 秒';
	}
}